package com.xntv.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.xntv.fast.pojo.Column;
import com.xntv.util.MD5Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fy
 * @version 1.0
 * @date 2020/12/23
 */
@Service
public class ColumnService {

    private static final Logger logger = LoggerFactory.getLogger(ColumnService.class);

    @Value("${tenantId}")
    private String tenantId;

    @Value("${tokenSuffix}")
    private String tokenSuffix;

    @Value("${getColumnsUrl}")
    private String url;

    @Resource
    private RestTemplate restTemplate;

    public List<Column> getColumns() {
        Map<String, String> params = assembleParams();
        logger.info("send request to: {}, 请求参数： {}", url, params);
        String response = restTemplate.getForObject(url + "?token={token}", String.class, params);
        Map<String, List<Column>> columnMap = JSON.parseObject(response, new TypeReference<Map<String, List<Column>>>() {});
        return columnMap.get("columnList");
    }

    private Map<String, String> assembleParams() {
        Map<String, String> params = new HashMap<>();
        params.put("token", MD5Utils.digestAsHex(tenantId + tokenSuffix));
        return params;
    }
}
